最後當然要將程式部署到雲端環境運行測試!
架構規劃時就設定好了最終目標,現在只差最後一小步。
現在的程式已經能從 S3 讀取資料、也可以串接到 Bedrock 呼叫模型,接下來,就該依照原先設計的架構圖,讓程式上到雲端環境執行!
如果不是協作開發,或只是要做簡單的功能測試,其實很適合在 Lambda 上直接實作。
不但可以直接在瀏覽器上編輯、還能立即測試跟發布服務,非常方便!
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Bedrock",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": "arn:aws:bedrock:ap-northeast-1:590184072539:inference-profile/apac.anthropic.claude-3-7-sonnet-20250219-v1:0"
}
]
}
設定說明
Action | Description |
---|---|
InvokeModel | 呼叫 Bedrock AI Model |
InvokeModelWithResponseStream | 用串流方式呼叫 Bedrock AI Model |
Resource | 指定只能使用 claude 3.7 sonnet |
如果需要使用多種模型,AWS 也支援 "Resource": []
如果要維持「最小權限原則」,就不建議寫成 "Resource":"*"
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadS3",
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:GetObject"
],
"Resource": "arn:aws:s3:::ithome-ironman-2025/*"
}
]
}
完成後授權設定後,回到 Lambda 的編輯頁面,直接在 Console 上調整程式碼:
為了方便在地端和雲端做切換,調整了 S3Service & BedrockService
# 調整 S3 Service
def read_s3_file_local(self, bucket_name: str, object_key: str, encoding: str = "utf-8"):
"""
地端呼叫使用,須帶入 sso token
"""
session = boto3.Session(profile_name="dev-s3-ironman2025")
client = session.client("s3")
return self.__read_s3_file(client, bucket_name, object_key, encoding)
def read_s3_file(self, bucket_name: str, object_key: str, encoding: str = "utf-8"):
"""
雲端呼叫使用,直接建立 s3 client
"""
client = boto3.client("s3")
return self.__read_s3_file(client, bucket_name, object_key, encoding)
def __read_s3_file(self, client, bucket_name: str, object_key: str, encoding: str ) -> str:
# 讀取 S3 檔案邏輯
在 BedrockService 也作了同樣的處理,這樣能便於本機端與雲端環境間切換測試,同時確保兩者執行邏輯一致
最後按下畫面左側的「Deploy」,等待發布完成就可以進行測試囉!
切換到「測試」分頁,目前的程式還不需要傳入值,可以直接按下「測試」
AWS Lambda 預設的逾時時間只有 3 秒,但這對呼叫大型模型來說肯定不夠。
經過幾次測試,Bedrock 的呼叫平均時間落在 35 秒上下... 所以需要調整一下逾時限制:
如果很習慣 VS Code,大概會覺得 Lambda 的介面異常親切,跟 VS Code 簡直就是雙胞胎!
好奇一查,還真的是:Introducing an enhanced in-console editing experience for AWS Lambda
AWS Lambda is introducing a new code editing experience in the AWS console based on the popular Code-OSS, Visual Studio Code Open Source code editor.
Visual Studio Code is the most popular IDE among developers according to the 2023 Stack Overflow Developer Survey. Integrating Code-OSS into the Lambda Console brings a familiar, accessible, and customizable interface to the in-browser code editing capabilities. This provides a coding experience that is substantially similar to working with function code locally. You can install selected extensions, apply preferred themes and settings, and use your familiar keyboard shortcuts and coding preferences.
大致意思是:根據 2023 年 Stack Overflow 開發者調查,Visual Studio Code 是最受歡迎的 IDE。AWS Lambda Console 引入了 VS Code 的開源版本 Code-OSS,為瀏覽器中的程式編輯功能帶來熟悉、易於使用且可自訂的介面。